package com.demo.project_template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.project_template.constant.GoldEnum;
import com.demo.project_template.entity.GoldExchange;
import com.demo.project_template.entity.UserGoldRecord;
import com.demo.project_template.entity.UserWallet;
import com.demo.project_template.exception.ErrorCodeException;
import com.demo.project_template.mapper.GoldExchangeMapper;
import com.demo.project_template.mapper.UserGoldRecordMapper;
import com.demo.project_template.mapper.UserWalletMapper;
import com.demo.project_template.service.UserWalletService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.project_template.vo.request.order.ExchangeVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户钱包 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:58
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService {

    @Resource
    private UserGoldRecordMapper userGoldRecordMapper;
    @Resource
    private GoldExchangeMapper goldExchangeMapper;
    @Override
    public void integralExchange(ExchangeVO exchangeVO) {
        //查询用户钱包余额
        UserWallet userWallet = getOne(new LambdaQueryWrapper<UserWallet>().eq(UserWallet::getUserId, exchangeVO.getUserId()));
        userWallet.setVersion(exchangeVO.getVersion());

        //查询金币兑换配置
        GoldExchange goldExchange = goldExchangeMapper.selectById(exchangeVO.getExchangeId());
        if (goldExchange.getIntegralCount()>userWallet.getIntegralCount()){
            throw new ErrorCodeException("剩余积分不足");
        }

        //处理用户钱包
        userWallet.setIntegralCount(userWallet.getIntegralCount()-goldExchange.getIntegralCount());
        userWallet.setGoldCount(userWallet.getGoldCount()+goldExchange.getGoldCount());
        boolean flag = updateById(userWallet);
        if (!flag){
            throw new ErrorCodeException("处理异常，请重试");
        }

        //添加金币变动记录
        UserGoldRecord userGoldRecord = new UserGoldRecord();
        userGoldRecord.setIsAdd("1");
        userGoldRecord.setUserId(exchangeVO.getUserId());
        userGoldRecord.setAmount(goldExchange.getGoldCount());
        userGoldRecord.setType(GoldEnum.EXCHANGE_ADD.getCode());
        userGoldRecord.setReason(GoldEnum.EXCHANGE_ADD.getName());
        userGoldRecordMapper.insert(userGoldRecord);

        //todo 添加积分变动记录
    }
}
